#coding: UTF-8
import os, json, types, re, time, logging
import tornado.web
import tornado.websocket
from tornado.ioloop import PeriodicCallback

from handlers.entity import player
from handlers.entity import gameScene

from handlers.gameDecorator import onmsg_api_chk

from handlers.gamefunc import * 
 
from configs import *
import data.userData

'''
{
	act_join_que         --加入寻找战斗对列 
	req-->>{
		act = "act_join_que"
		basedata = {...},
		body = {

		}
	}

	rep<<--{
		r = svrstatu,
		error = r!=0 then '‘
		data = {
			ret = 0,
			...
		}
	}
}
'''

'''
	
'''

#websocket
class fightHandler(tornado.websocket.WebSocketHandler):
	
	_clis = set()
	_scenes = set()

	#=======================Override=========================

	def initialize(self):
		print ("initluze fighthandler")
		#schedule		
		# def cc():
		# 	logging.info("tests!schedule")	
		# aa = PeriodicCallback(cc, 1000)
		# aa.start()
	
	# def open(self , uidstr):
	# 	logging.info("@Con open! A new comer {%s}start to fight."%uidstr)
	# 	playerobjs = self.__chk_player_obj(uidstr)
		
	# 	#handler--->>add player
	# 	self._clis.add(self)
		
	# 	ret = None
	# 	repdic = dict(
	# 		ret = None,
	# 		addtime = time.time(),
	# 		scenedata = dict()
	# 		)
	# 	if len(playerobjs) == 1:
	# 		(ret, sceneobj) = self.__singleplayer_addto_sceen(playerobjs[0])
	# 	else:
	# 		(ret, sceneobj) = self.__mulityplayer_addto_scene(playerobjs)

	# 	repdic["ret"] = ret
	# 	if sceneobj:
	# 		repdic["scenedata"] = sceneobj.get_scenedata()
	# 	self.write_message(shareRet.raiseRet(repdic)


	@onmsg_api_chk
	def on_message(self , message , ret , rcv_dict , tmp = ""):
		logging.info("@Rcv the message-->%s" % message)
		logging.info("@Rcv the ret-->%s" % ret)
		logging.info("@Rcv the rcv_dict-->%s" % rcv_dict)

		self.write_message("ok!" , True)
	def on_pong(self , data):
		self._potime = time.time()
		logging.info(self._potime)
		logging.info("final---!!")
		logging.info ((self._potime - self._pitime) * 1000)


	def on_close(self):
		# for user in self._clis:
		# 	if (self.user['uid'] == i['uid']):
		# 		self._clis.remove(user)
		# self.user = None 
		print "websocket close"
	#=======================Logic=========================
	def __singleplayer_addto_sceen(self, playerobj):
		tarscene = None
		if len(self._scenes) == 0:
			tarscene = gmaeScene(ConfigScene.SCENE["fight"])
			self._scenes.add(tarscene)

		#todo 多线程去匹配
		ret = None
		for scene in self._scenes:
			if FuncScene.getSceneWeight(scene.get_scenedata()) == 1:
				tarscene = scene
				ret = scene.add_player(playerobj)
		if not ret:
			tarscene = gmaeScene(ConfigScene.SCENE["fight"])
			self._scenes.add(tarscene)
			ret = scene.add_player(playerobj)
		return ret , tarscene

	def __mulityplayer_addto_scene(self, playerobjs):
		#todo 多线程去添加匹配
		for player in playerobjs:
			scenedata = player.get_scenedata()
			if scenedata:
				print ("relaunch to same scene")
			else:
				scene = gmaeScene(ConfigScene.SCENE["fight"])	

	def __chk_player_obj(self, uidstr):
		uids = uidstr.split("+")
		playerobjs = []
		for uid in uids:
			obj = player(userData.find_by_uid(uid))
			playerobjs.append(obj)
		return playerobjs

	#=======================MSG=========================

	def msg_enter_fightscene(self , playeruid , entertype , sceneid = 0):
		rval = {}
		if entertype == kEnterType['new']:
			newscene = fightScene()
			self._scenes.append(newscene)
			isenter = newscene.dispatch('eventEnter')
		elif entertype == kEnterType['join']:
			isenter = newscene.dispatch('eventJoin')
		return rval